<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>CM MapDownLoader</title>
    <!-- jquery -->
    <script src="/thirdLib/jq/jquery-3.3.1.min.js"></script>

    <!-- BootStrap -->
    <link rel="stylesheet" href="/thirdLib/bootstrap-3.3.7/css/bootstrap.min.css"/>
    <script src="/thirdLib/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <!--阿里样式-->
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
    <style type="text/css">
        html, body, #container {
            height: 100%;
        }

        .btn {
            width: 7rem;
            margin-left: 5rem;
        }
    </style>
</head>
<body>
<div id="container"></div>

<div class="input-card" style="width: 32rem;">
    <h3>领图下载器</h3>
    <h4>下载区域</h4>
    <div class="input-item">
        <div class="input-item-prepend"><span class="input-item-text">省市区</span></div>
        <select id='province' style="width:100px" onchange='search(this)'></select>
    </div>
    <div class="input-item">
        <div class="input-item-prepend"><span class="input-item-text">地级市</span></div>
        <select id='city' style="width:100px" onchange='search(this)'></select>
    </div>
    <div class="input-item">
        <div class="input-item-prepend"><span class="input-item-text">区县</span></div>
        <select id='district' style="width:100px" onchange='search(this)'></select>
    </div>
    <h4>下载设置</h4>
    <div class="input-item">
        <div class="input-item-prepend"><span class="input-item-text">保存路径</span></div>
        <input id='filePath' class="input-item" type="text" placeholder="输入文件保存路径" style="width:100px"/>
    </div>
    <div class="input-item">
        <div class="input-item-prepend"><span class="input-item-text">是否覆盖</span></div>
        <select id='append' style="width:100px">
            <option value="true">是</option>
            <option value="false">否</option>
        </select>
    </div>
    <h4>下载级别(下载瓦片的级别)</h4>
    <div class="input-item">
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='7'>7&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='8'>8&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='9'>9&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='10'>10&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='11'>11&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='12'>12&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='13'>13&nbsp;&nbsp;
    </div>
    <div class="input-item">
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='14'>14&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='15'>15&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='16'>16&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='17'>17&nbsp;&nbsp;
        <input type="checkbox" name='mapLevel' onclick="updateLevel(this)" value='18'>18&nbsp;&nbsp;
    </div>
    <div class="input-item">
        <input id="downLoad" type="button" class="btn" onclick="downLoadMap()" value="下载"/>
        <input id="cancel" type="button" class="btn" onclick="cancelDownLoad()" value="取消"/>
    </div>
    <div class="input-item">
        <div class="progress" id="progressDiv" style="width: 100%" hidden>
            <div class="progress-bar" id="progressBar" role="progressbar" aria-valuenow="60" aria-valuemin="50"
                 aria-valuemax="100" style="width: 0%;">
                0%
            </div>
        </div>
    </div>
    <h4 id="socketMsg"></h4>


</div>
<script type="text/javascript"
        src="https://webapi.amap.com/maps?v=1.4.15&key=a335cc8ac3803361df25094aadc62a53&plugin=AMap.DistrictSearch"></script>
<script type="text/javascript">
    var map, district, polygons = [];
    var citySelect = document.getElementById('city');
    var districtSelect = document.getElementById('district');
    var socketMsgEle = document.getElementById("socketMsg");
    // 下载的地区名
    var mapName = '';
    // 记录边界的最大和最小坐标
    var minLng = '';
    var maxLng = '';
    var minLat = '';
    var maxLat = '';
    // 下载层级
    var levelList = [];
    // 下载地图的长连接
    var websocket = null;

    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://127.0.0.1:9090/downLoadMapSocket/downloadMap");
        // 监听服务器端发送来的消息
        websocket.onmessage = function (event) {

            // socketMsgEle.innerHTML = '<p style="color: green">' + event.data.message + '</p>';
            var result = JSON.parse(event.data);
            if (result.type == 0) { // 下载文件信息确认
                $("#progressBar").width("0%");
                $("#progressBar").html("0%");
                // 构建提示信息
                var hintMsg = '下载地区: ' + mapName + '\n保存路径: ' + $("#filePath").val() + '\n文件个数: ' + result.body.countFileNum + '\n预计大小: ' + result.body.countFileSize;
                if (confirm(hintMsg)) {
                    // 开始进行下载
                    downLoadMapStart();
                }
            }

            if (result.type == 2) { // 系统类信息(展示在交互框内)
                if (result.status == 'success') {
                    socketMsgEle.innerHTML = '<p style="color: green">' + result.message + '</p>';
                } else {
                    socketMsgEle.innerHTML = '<p style="color: red">' + result.message + '</p>';
                    $("#progressDiv").hide();
                }
            }

            if (result.type == 3) { // 更新下载进度
                var schedule = result.message;
                if (schedule > 100){
                    schedule = 99;
                }
                $("#progressBar").width(schedule + "%");
                $("#progressBar").html(schedule + "%");
            }
            if (result.type == 4) { // 下载完成,隐藏进度条
                $("#progressBar").width(100 + "%");
                $("#progressBar").html(100 + "%");
            }
            if (result.type == 6) { // 连接信息
                $("#filePath").val(result.message);
            }
        }
        // 连接出错时
        websocket.onerror = function (e) {
            socketMsgEle.innerHTML += '<p style="color: red">WebSocket连接出错</p>';
        }
    } else {
        socketMsgEle.innerHTML = '<p style="color: red">当前浏览器不支持websocket!!</p>';
    }


    map = new AMap.Map('container', {
        resizeEnable: true,
        center: [116.30946, 39.937629],
        zoom: 3
    });
    //行政区划查询
    var opts = {
        subdistrict: 1,   //返回下一级行政区
        showbiz: false  //最后一级返回街道信息
    };
    district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
    district.search('中国', function (status, result) {
        if (status == 'complete') {
            getData(result.districtList[0]);
        }
    });

    // 选择下载层级
    function updateLevel(event) {
        if (event.checked) {
            levelList.push(event.value);
        } else {
            // 否则移除
            var idx1 = levelList.indexOf(event.value);
            levelList.splice(idx1, 1);
        }
    }

    // 下载地图
    function downLoadMap() {
        // 校验信息
        if (verifyParam()) {
            // 开始建立连接
            // $("#filePath").val($("#filePath").val());
            sendReady();
        }
    }

    // 准备下载
    function sendReady() {
        // 开始发送下载命令
        var body = {
            level: levelList,
            minLng: minLng,
            minLat: minLat,
            maxLng: maxLng,
            maxLat: maxLat
        };
        var data = {
            type: 0,
            body: body
        }
        websocket.send(JSON.stringify(data));
    }

    // 取消下载
    function cancelDownLoad() {
        socketMsgEle.innerHTML = '<p style="color: green">准备停止...</p>';
        var data = {
            type: 5
        }
        websocket.send(JSON.stringify(data));
    }

    // 开始下载
    function downLoadMapStart() {
        // 开始发送下载命令
        var filePath = $("#filePath").val();
        // 是否覆盖下载
        var appendFlag = $("#append").val();
        var body = {
            level: levelList,
            appendFlag: appendFlag,
            minLng: minLng,
            minLat: minLat,
            maxLng: maxLng,
            maxLat: maxLat,
            filePath: filePath
        };
        var data = {
            type: 1,
            body: body
        };
        websocket.send(JSON.stringify(data));
        $("#progressDiv").show();
    }


    function verifyParam() {
        if (levelList.length == 0) {
            alert("请选择下载的级别");
            return false;
        }
        if (minLng == '' || maxLng == '' || minLat == '' || maxLat == '') {
            alert("选择区域有误,请重新选择");
        } else {
            if (minLng > maxLng || minLat > maxLat) {
                alert("选择区域有误,请重新选择");
                return false;
            }
        }
        if (!$("#filePath") || $("#filePath") == '') {
            alert("请输入文件保存路径");
            return false;
        }
        return true;
    }

    function getData(data, level) {
        var bounds = data.boundaries;
        mapName = data.name;
        // 清空下载边界
        minLng = '';
        maxLng = '';
        minLat = '';
        maxLat = '';
        if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
                var boundLine = bounds[i];
                var polygon = new AMap.Polygon({
                    map: map,
                    strokeWeight: 1,
                    strokeColor: '#0091ea',
                    fillColor: '#80d8ff',
                    fillOpacity: 0.2,
                    path: boundLine
                });
                polygons.push(polygon);
                for (var idx = 0, len = boundLine.length; idx < len; idx++) {
                    // 获取出最大最小的经纬集合
                    if (minLng && minLng != '') {
                        if (boundLine[idx].lng < minLng) {
                            minLng = boundLine[idx].lng;
                        }
                    } else {
                        minLng = boundLine[idx].lng;
                    }

                    if (maxLng && maxLng != '') {
                        if (boundLine[idx].lng > maxLng) {
                            maxLng = boundLine[idx].lng;
                        }
                    } else {
                        maxLng = boundLine[idx].lng;
                    }

                    if (minLat && minLat != '') {
                        if (boundLine[idx].lat < minLat) {
                            minLat = boundLine[idx].lat;
                        }
                    } else {
                        minLat = boundLine[idx].lat;
                    }

                    if (maxLat && maxLat != '') {
                        if (boundLine[idx].lat > maxLat) {
                            maxLat = boundLine[idx].lat;
                        }
                    } else {
                        maxLat = boundLine[idx].lat;
                    }
                }
            }
            map.setFitView();//地图自适应
        }

        //清空下一级别的下拉列表
        if (level === 'province') {
            citySelect.innerHTML = '';
            districtSelect.innerHTML = '';
        } else if (level === 'city') {
            districtSelect.innerHTML = '';
        }

        var subList = data.districtList;
        if (subList) {
            var contentSub = new Option('--请选择--');
            var curlevel = subList[0].level;
            if (curlevel != 'street') {
                var curList = document.querySelector('#' + curlevel);
                curList.add(contentSub);
                for (var i = 0, l = subList.length; i < l; i++) {
                    var name = subList[i].name;
                    var levelSub = subList[i].level;
                    var cityCode = subList[i].citycode;
                    contentSub = new Option(name);
                    contentSub.setAttribute("value", levelSub);
                    contentSub.center = subList[i].center;
                    contentSub.adcode = subList[i].adcode;
                    curList.add(contentSub);
                }
            }
        }

    }

    function search(obj) {
        //清除地图上所有覆盖物
        for (var i = 0, l = polygons.length; i < l; i++) {
            polygons[i].setMap(null);
        }
        var option = obj[obj.options.selectedIndex];
        var keyword = option.text; //关键字
        var adcode = option.adcode;
        district.setLevel(option.value); //行政区级别
        district.setExtensions('all');
        //行政区查询
        //按照adcode进行查询可以保证数据返回的唯一性
        console.log(adcode)
        district.search(adcode, function (status, result) {
            if (status === 'complete') {
                getData(result.districtList[0], obj.id);
            }
        });
    }

    function setCenter(obj) {
        map.setCenter(obj[obj.options.selectedIndex].center)
    }
</script>
<script type="text/javascript" src="https://webapi.amap.com/demos/js/liteToolbar.js"></script>

</body>
</html>